10 DEFINT A-Z:L=0:DIM B(15),G(8,2),CMP(9,1)
11 FOR I=0 TO 13:B(I)=2^I:NEXT I
20 INPUT "Enable Mastermind (Y/N)";S$:IF S$="Y" or S$="y" THEN MT=1
30 WHILE 1:CLS:PRINT "*** Bulls and Cows Solver ***":IF L>0 THEN PRINT ""
40 FOR I=0 TO L-1:PRINT USING "#. ";I+1;:N=G(I,0):GOSUB 250
50 N=G(I,1):PRINT USING " #A#B";N\16,N AND 15:NEXT I
60 PRINT "":INPUT "[A]dd/[D]el/[E]dit/[C]alculate/[Q]uit";K$
71 IF K$="Q" OR K$="q" THEN CLS:END
72 IF K$="C" OR K$="c" THEN GOSUB 300
73 IF K$="A" OR K$="a" THEN IF L<8 THEN I=L:L=L+1:GOSUB 130
74 IF K$="D" OR K$="d" THEN GOSUB 100
75 IF K$="E" OR K$="e" THEN GOSUB 120
80 WEND
100 REM Del
101 INPUT "Which one";D:IF D<1 OR D>L THEN RETURN
110 L=L-1:FOR I=D-1 TO L-1:G(I,0)=G(I+1,0):G(I,1)=G(I+1,1):NEXT I:RETURN
120 REM Edit
121 INPUT "Which one";I:IF I<1 OR I>L THEN RETURN ELSE I=I-1
130 PS=0:WHILE PS=0:PS=1:INPUT "Guess,A,B: ",N,A,B
140 IF MT=0 THEN GOSUB 200:IF R=0 THEN PS=0:PRINT "Duplicated digits"
150 IF A+B>4 THEN PS=0:PRINT "Invalid input"
160 WEND:G(I,0)=N:G(I,1)=(A*16) OR B:RETURN
200 R=0:M=B(N MOD 10):D=B((N\10) MOD 10)
210 IF (D AND M)=0 THEN M=M OR D ELSE RETURN
220 D=B((N\100) MOD 10):IF (D AND M)=0 THEN M=M OR D ELSE RETURN
230 D=B(N\1000):IF (D AND M)=0 THEN R=1
240 RETURN
250 IF N<10   THEN PRINT USING "000#";N;:RETURN
251 IF N<100  THEN PRINT USING "00##";N;:RETURN
252 IF N<1000 THEN PRINT USING "0###";N;:RETURN
253 PRINT USING "####";N;:RETURN
300 IF MT=0 THEN N=123:FIN=9876 ELSE N=0:FIN=9999
310 PRINT "Press Esc to stop calculation.":CNT=0:RN=1
320 WHILE N<=FIN AND RN=1:IF MT=0 THEN GOSUB 200:IF R=0 THEN GOTO 380
340 FOR I=0 TO L-1:A=G(I,0):B=N:GOSUB 400:IF R<>G(I,1) THEN GOTO 380
350 NEXT I:GOSUB 250:CNT=CNT+1
360 IF (CNT MOD 16)=0 THEN PRINT "":GOSUB 600 ELSE PRINT " ";
380 N=N+1:IF INKEY$=CHR$(27) THEN RN=0
385 WEND:IF (CNT MOD 16)<>0 THEN PRINT ""
390 IF RN<>2 THEN PRINT "Press any key to back.";:K$=INPUT$(1)
395 RETURN
400 R=0:IF A=B THEN R=&H40:RETURN
410 DA=A MOD 10:DB=B MOD 10
420 IF DA=DB THEN R=R+16 ELSE CMP(DA,0)=CMP(DA,0)+1:CMP(DB,1)=CMP(DB,1)+1
430 DA=(A\10) MOD 10:DB=(B\10) MOD 10
440 IF DA=DB THEN R=R+16 ELSE CMP(DA,0)=CMP(DA,0)+1:CMP(DB,1)=CMP(DB,1)+1
450 DA=(A\100) MOD 10:DB=(B\100) MOD 10
460 IF DA=DB THEN R=R+16 ELSE CMP(DA,0)=CMP(DA,0)+1:CMP(DB,1)=CMP(DB,1)+1
470 DA=A\1000:DB=B\1000
480 IF DA=DB THEN R=R+16 ELSE CMP(DA,0)=CMP(DA,0)+1:CMP(DB,1)=CMP(DB,1)+1
490 FOR I0=0 TO 9:DA=0:DB=0:SWAP DA,CMP(I0,0):SWAP DB,CMP(I0,1)
500 IF DA<DB THEN R=R+DA ELSE R=R+DB
510 NEXT I0:RETURN
600 IF (CNT MOD (16*22))<>0 THEN RETURN
610 PRINT "Press any key to continue.";:K$=INPUT$(1)
620 IF K$=CHR$(27) THEN RN=2 ELSE PRINT ""
630 RETURN
